<?php

namespace app\beautiful\model\mall;

use app\beautiful\model\goods\GoodsOtherSkuDetailModel;
use app\beautiful\model\LevelModel;
use app\common\model\CommonModel;
use think\facade\Db;


class GoodsSkuModel extends CommonModel{

    protected  $name = 'beautiful_goods_sku';

    protected  $pk   = 'sku_id';

    public function getById($where,$field='*')
    {
        $json = [];
        if($field=='*'){
            $json[] = 'discount_detail';
        }else{
            $arr = explode(',',$field);
            if(in_array('discount_detail',$arr)){
                $json[] = 'discount_detail';
            }
        }

        $list = $this->where($where)->field($field)->json($json,true)->find();
        if($list) $list = $list->toArray();

        return $list;
    }
    public static function up($data,$where){
        $res = self::update($data,$where);
        return $res;

    }
    public function unit()

    {

        return $this->hasOne(GoodsOtherSkuDetailModel::class,'other_sku_detail_id','unit_id');

    }
    public static function list($where,$order,$page=0,$limit=0,$field='*'){
        $query = Db::name('beautiful_goods_sku')->alias('gs')
            ->leftJoin('beautiful_goods_other_sku_detail sd','sd.other_sku_detail_id=gs.unit_id')
            ->where(['gs.is_delete'=>0])
            ->when(isset($where['shop_id']),function ($query) use ($where){
                $query->where(['gs.shop_id'=>$where['shop_id']]);
            })
            ->when(isset($where['goods_id']),function ($query) use ($where){
                $query->where(['gs.goods_id'=>$where['goods_id']]);
            })
            ->field($field);
        if($page>0) $query = $query->page($page);
        if($limit>0) $query = $query->limit($limit);
        $list=$query->order($order)->page($page)
            ->select()
            ->toArray();
        if(!empty($list)){
            if(isset($where['goods_id'])){
                $goods = \app\cash\model\GoodsModel::info(['goods_id'=>$where['goods_id']]);
            }
            $level_model = new LevelModel();
            foreach ($list as &$v){
                $v['origin_type'] = isset($goods) && $goods?$goods['origin_type']:1;
                $v['discount_detail'] = json_decode($v['discount_detail'],true);
                if($v['discount_detail']){
                    foreach ($v['discount_detail'] as $k=>$vv){
                        $level = $level_model->getById(['level_id'=>$vv['level_id'],'shop_id'=>$v['shop_id'],'is_delete'=>0]);
                        $v['discount_detail'][$k]['name']=$level?$level['name']:'';
                    }
                }
            }

        }

        return $list;
    }
}

